import React, { useEffect, useState } from "react";
//import qs from 'qs';
import { req } from "@/common/methods";
import {
  Table,
  Modal,
  Button,
  Space,
  message,
  Image,
  Input,
  Radio,
  Spin,
  Tag,
} from "antd";
import {
  CloseCircleOutlined,
  CloseOutlined,
  SearchOutlined,
  FileAddOutlined,
  PlusOutlined,
} from "@ant-design/icons";

import EditGoods from "@/components/EditGoods/index.tsx";
import GoodsDetail from "@/components/GoodsDetail/index.tsx";

import styles from "./index.module.scss";

import ChangeCount from "@/components/ChangeCount";

import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import type { FilterValue, SorterResult } from "antd/es/table/interface";
import { isHtmlElement } from "node_modules/react-router-dom/dist/dom";

interface DataType {
  name: {
    first: string;
    last: string;
  };
  gender: string;
  email: string;
  login: {
    uuid: string;
  };
  count: number;
}

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { confirm, error, info } = Modal;
const { Search } = Input;

const getRandomuserParams = (params: TableParams) => ({
  results: params.pagination?.pageSize,
  page: params.pagination?.current,
  ...params,
});

const Goods: React.FC = () => {
  const [allLoading, setAllLoading] = useState(true);
  const [dataCategory, setDataCategory] = useState([]);
  const fetchBaseData = () => {
    req("/api/category/get")
      .then((data) => {
        setDataCategory(data);
        setAllLoading(false);
      })
      .catch((error) => {
        Modal.error({
          title: "初始化失败",
          content: (
            <>
              该页面初始化失败，请刷新重试，或与王阳联系
              <br />
              参考信息:{"" + error}
            </>
          ),
        });
      });
  };
  useEffect(() => fetchBaseData(), []);
  const [data, setData] = useState<DataType[]>([]);
  const [modalopen, setModalopen] = useState(false);
  const [tempCurrentItem, setTempCurrentItem] = useState({});
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const columns: ColumnsType<DataType> = [
    {
      title: "名称",
      dataIndex: "name",
      sorter: (a, b) => {
        const v1 = ("" + a.name).charAt(0);
        const v2 = ("" + b.name).charAt(0);
        return v1.localeCompare(v2, "zh-CN");
      },
      //ender: (name) => `${name.first} ${name.last}`,
      //width: '20%',
      render(record, currentItem) {
        return (
          <>
            <a
              href="#"
              onClick={(e) => {
                e.preventDefault();
                Modal.info({
                  title: record + " - 物品详情",
                  content: (
                    <>
                      <GoodsDetail
                        detail={currentItem}
                        dataCategory={dataCategory}
                      />
                    </>
                  ),
                  width: 970,
                });
              }}
            >
              {record}
            </a>
          </>
        );
      },
      filters: (() => {
        let res = [];
        try {
          res = data
            .map((item) => item.name)
            .filter((item1, index1, arr1) => arr1.indexOf(item1) == index1)
            .map((item2) => ({ text: item2, value: item2 }));
        } catch (e) {
          message.error("" + e);
        }
        //console.log(res);
        return res;
      })(),
      filterMode: "tree",
      filterSearch: true,
      onFilter: (value: string, record) => ("" + record.name).startsWith(value),
    },
    {
      title: "类别",
      dataIndex: "category",
      // filters: [
      //   { text: 'Male', value: 'male' },
      //   { text: 'Female', value: 'female' },
      // ],
      //width: '20%',
      sorter: (a, b) => {
        const v1 = ("" + a.category).charAt(0);
        const v2 = ("" + b.category).charAt(0);
        return v1.localeCompare(v2, "zh-CN");
      },
      render(category) {
        return (
          <>
            <div
              style={
                dataCategory.find((item) => item.id === category)
                  ? {}
                  : { color: "red" }
              }
            >
              {dataCategory.find((item) => item.id === category)?.name ||
                `未知分类[${category}]`}
            </div>
            {/* {[undefined,'医疗用品','生活用品'][category] || '未知'} */}
          </>
        );
      },
    },
    {
      title: "区域",
      dataIndex: "local",
      render(local) {
        return <>{[undefined, "东仓"][local] || "未知"}</>;
      },
    },
    {
      title: "参考图",
      dataIndex: "img",
      render: (img) => {
        return img ? (
          <>
            <Image src={img} height={25} />
          </>
        ) : (
          ""
        );
      },
    },
    {
      title: "简介",
      dataIndex: "detail",
      render(detail, currentItem) {
        return ("" + detail).length > 15 ? (
          <a
            onClick={() =>
              Modal.info({
                title: currentItem.name && currentItem.name + " - " + "简介",
                content: <>{"" + detail}</>,
              })
            }
          >
            {("" + detail).substring(0, 12) + `...`}
          </a>
        ) : (
          <>{detail}</>
        );
      },
    },
    {
      title: "规格",
      dataIndex: "specs",
    },
    {
      title: "单位",
      dataIndex: "unit",
      sorter: (a, b) => {
        const v1 = ("" + a.unit).charAt(0);
        const v2 = ("" + b.unit).charAt(0);
        return v1.localeCompare(v2, "zh-CN");
      },
    },
    {
      title: "数量",
      dataIndex: "count",
      sorter: {
        compare: (a, b) => a.count - b.count,
        multiple: 3,
      },
    },
    {
      title: "别名",
      dataIndex: "another_name",
      render(record) {
        return (
          <>
            {record &&
              ("" + record)
                .trim()
                .replace(/\,|\，/g, " ")
                .split(" ")
                .map((item, index) => {
                  return <Tag key={index}>{item}</Tag>;
                })}
          </>
        );
      },
    },
    {
      title: "添置时间",
      dataIndex: "create_time",
      render(timeString) {
        if (timeString) {
          const date = new Date(timeString);
          const y = date.getFullYear();
          const m = date.getMonth() + 1;
          const d = date.getDate();
          return (
            <>
              <span title={timeString}>{`${y}-${m}-${d}`}</span>
            </>
          );
        }
      },
      sorter: (a, b) => {
        const v1 = "" + a.create_time;
        const v2 = "" + b.create_time;
        return v1.localeCompare(v2, "zh-CN");
      },
      filters: (() => {
        let res = [];
        try {
          res = data
            .map((item) => item.create_time)
            .map((item0) => {
              // const date = new Date(item0);
              // const y = date.getFullYear();
              // const m = date.getMonth() + 1;
              // const d = date.getDate();
              // return `${y}-${m}-${d}`;
              return item0 ? ("" + item0).substring(0, 10) : "";
            })
            .filter(
              (item1, index1, arr1) => arr1.indexOf(item1) == index1 && item1
            )
            .map((item2) => ({ text: item2, value: item2 }));
        } catch (e) {
          message.error("" + e);
        }
        return res;
      })(),
      onFilter: (value: string, record) =>
        ("" + record.create_time).startsWith(value),
    },
    {
      title: "修改时间",
      dataIndex: "update_time",
      render(timeString) {
        if (timeString) {
          const date = new Date(timeString);
          const y = date.getFullYear();
          const m = date.getMonth() + 1;
          const d = date.getDate();
          return (
            <>
              <span title={timeString}>{`${y}-${m}-${d}`}</span>
            </>
          );
        }
      },
      sorter: (a, b) => {
        const v1 = "" + a.update_time;
        const v2 = "" + b.update_time;
        return v1.localeCompare(v2, "zh-CN");
      },
      filters: (() => {
        let res = [];
        try {
          res = data
            .map((item) => item.update_time)
            .map((item0) => {
              // const date = new Date(item0);
              // const y = date.getFullYear();
              // const m = date.getMonth() + 1;
              // const d = date.getDate();
              // return `${y}-${m}-${d}`;
              return item0 ? ("" + item0).substring(0, 11) : "";
            })
            .filter(
              (item1, index1, arr1) => arr1.indexOf(item1) == index1 && item1
            )
            .map((item2) => ({ text: item2, value: item2 }));
        } catch (e) {
          message.error("" + e);
        }
        return res;
      })(),
      onFilter: (value: string, record) =>
        ("" + record.update_time).startsWith(value),
    },
    {
      title: "操作",
      dataIndex: "id",
      render(id, currentItem, column) {
        return (
          <>
            <Space>
              <Button
                size="small"
                type="primary"
                onClick={() => {
                  info({
                    title: `改数量 - id:${id} - name:${currentItem.name}`,
                    content: (
                      <>
                        <ChangeCount
                          goods_id={id}
                          goods_name={currentItem.name}
                          before_count={currentItem.count}
                          doClose={() => doClose()}
                        />
                      </>
                    ),
                    footer: null,
                  });
                }}
              >
                改数量
              </Button>
              <Button
                size="small"
                type="primary"
                onClick={() =>
                  info({
                    title: `编辑 - id:${id} - name:${currentItem.name}`,
                    content: (
                      <>
                        <EditGoods
                          ty="edit"
                          defaultData={currentItem}
                          doClose={doClose}
                          dataCategory={dataCategory}
                        />
                      </>
                    ),
                    closeIcon: <CloseOutlined />,
                    okText: "取消并关闭窗口",
                    footer: null,
                  })
                }
              >
                编辑
              </Button>
              <Button
                size="small"
                type="primary"
                danger
                onClick={() =>
                  confirm({
                    title: `删除 - id:${id} - name:${currentItem.name}`,
                    content: (
                      <>
                        <div>
                          您即将执行删除操作，请确认！
                          <font color="red">
                            删除后与之关联的所有出入库单名称都将无法显示，此操作不可逆
                          </font>
                          ，确定要删除吗？
                        </div>
                      </>
                    ),
                    onOk(eF) {
                      eF && eF();
                      req("/api/goods/delete", { id }, "post")
                        .then(() => {
                          message.success("删除成功");
                          fetchData();
                        })
                        .catch((errMsg) => {
                          error({
                            title: "操作出错",
                            content: (
                              <>
                                本条数据有可能删除失败
                                <br />
                                <pre>{"" + errMsg}</pre>
                              </>
                            ),
                          });
                        });
                    },
                  })
                }
              >
                删除
              </Button>
            </Space>
          </>
        );
      },
    },
  ];
  //功能块,制作搜索方式
  const [searchText, setSearchText] = useState("");
  const [searchLoading, setSearchLoading] = useState(false);
  //功能块category
  const [category, setCategory] = useState(0);
  //读取数据
  const fetchData = () => {
    //query={}
    //console.log('请求前',query);
    //console.log('执行了fetchData');
    setLoading(true);
    return req("/api/goods/get_all", { category, search: searchText }, "get")
      .then((data) => {
        //console.log(data);
        setData(data);
        setLoading(false);
        //setSearchLoading(false);
      })
      .catch((msg) => {
        error({
          title: "系统出错",
          content: (
            <div>
              <pre>{"" + msg}</pre>
            </div>
          ),
        });
      });
    // setLoading(true);
    // fetch(`https://randomuser.me/api?${qs.stringify(getRandomuserParams(tableParams))}`)
    //   .then((res) => res.json())
    //   .then(({ results }) => {
    //     setData(results);
    //     setLoading(false);
    //     setTableParams({
    //       ...tableParams,
    //       pagination: {
    //         ...tableParams.pagination,
    //         total: 200,
    //         // 200 is mock data, you should read it from server
    //         // total: data.totalCount,
    //       },
    //     });
    //   });
  };

  useEffect(() => {
    fetchData();
    //console.log('执行effect');
  }, [JSON.stringify(tableParams), category, searchText]);

  const handleTableChange = (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue>,
    sorter: SorterResult<DataType>
  ) => {
    setTableParams({
      pagination,
      filters,
      ...sorter,
    });

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setData([]);
    }
  };
  const doClose = () => {
    //alert('使用了');
    //setCategory('');
    //setSearchText('');
    // setTimeout(()=>{
    //   fetchData();
    // },30)
    fetchData();
  };

  return (
    <>
      {allLoading ? (
        <Spin />
      ) : (
        <div className="all-show">
          <div className={styles.toolbar}>
            <Space>
              <Radio.Group buttonStyle="solid" value={category}>
                {[{ id: 0, name: "全部" }, ...dataCategory].map((item) => (
                  <Radio.Button
                    key={item.id}
                    value={item.id}
                    onClick={() => {
                      setCategory(item.id);
                      //fetchData();
                      //fetchData({category:item.id,search:searchText});
                    }}
                  >
                    {item.name}
                  </Radio.Button>
                ))}
              </Radio.Group>
              <Search
                placeholder="输入物品的名称"
                enterButton="搜索物品"
                icon={<SearchOutlined />}
                size="middle"
                loading={searchLoading}
                onSearch={(search) => {
                  //setSearchLoading(true);
                  setSearchText(search);
                  // setTimeout(()=>{
                  //   fetchData().finally(()=>setSearchLoading(false));
                  //   //fetchData({search,category}).finally(()=>setSearchLoading(false));
                  // },30);
                }}
              />
              {searchText && (
                <Button
                  danger
                  onClick={() => {
                    setSearchText("");
                    // setTimeout(()=>{
                    //   fetchData().finally(()=>setSearchLoading(false));
                    // },30);
                  }}
                >
                  取消搜索
                </Button>
              )}
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() =>
                  info({
                    icon: <FileAddOutlined />,
                    title: `添加物品`,
                    content: (
                      <>
                        <EditGoods
                          ty="create"
                          defaultData={{}}
                          doClose={doClose}
                          dataCategory={dataCategory}
                        />
                      </>
                    ),
                    closeIcon: <CloseOutlined />,
                    okText: "取消并关闭窗口",
                    footer: null,
                  })
                }
              >
                添加物品
              </Button>
            </Space>
          </div>
          {/* <div className={styles['radio-toolbar']}>
        <Radio.Group buttonStyle="solid" value={category}>
          {[
            {id:0,name:'全部'},{id:1,name:'医疗用品'},{id:2,name:'生活办公'}
          ].map(item => <Radio.Button key={item.id} value={item.id} onClick={() => {
            setCategory(item.id);
            fetchData({category:item.id,search:searchText});
          }}>{item.name}</Radio.Button>)}
        </Radio.Group>
      </div> */}
          <Table
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={data}
            pagination={tableParams.pagination}
            loading={loading}
            onChange={handleTableChange}
            rowSelection={{
              fixed: true,
              //type:'radio'
            }}
          />
          {/* <Modal
          title=""
          style={{ top: 20 }}
          open={modalopen}
          onCancel={() => setModalopen(false)}
          footer={false}
          title="修改"
        >
          <EditGoods ty='edit' defaultData={tempCurrentItem} doClose={()=>{}}/>
        </Modal> */}
        </div>
      )}
    </>
  );
};

export default Goods;
